package com.itboye.api.helper;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * Created by 1.
 * Date:  2016-10-24
 * Copyright @2016 www.itboye.com  杭州博也科技有限公司
 */
public class PartFileHelper implements MultipartFile {

    private String fname;
    private String ftype;
    private String fdata;

    public void init(String fname,String ftype,String fdata){
        this.fdata = fdata;
        this.fname = fname;
        this.ftype = ftype;
    }
    public String getName() {
        return fname;
    }

    public String getOriginalFilename() {
        return fname;
    }

    public String getContentType() {
        return "image/jpg";
    }

    public boolean isEmpty() {
        return false;
    }

    public long getSize() {
        try {
            return  getBytes().length;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  0;
    }

    public byte[] getBytes() throws IOException {
        return fdata.getBytes();
    }

    public InputStream getInputStream() throws IOException {
        return new FileInputStream(fdata);
    }

    public void transferTo(File file) throws IOException, IllegalStateException {

        FileOutputStream writer = null;
        try {
            Base64.Decoder decoder = Base64.getMimeDecoder();
            writer = new FileOutputStream(file);
            byte[] decoderBytes = decoder.decode(fdata);
            writer.write(decoderBytes);
        }catch (IOException e){

        }finally {
            if(writer != null){
                writer.flush();
                writer.close();
            }
        }
    }

}
